<template>
	<div class="wrapper" v-loading="loading">
		<div class="filter row items-center">
			<div class="f-item row items-center">
				<span>预警机构：</span>
				<el-tree-select
					filterable
					check-strictly
					node-key="orgNo"
					:props="{
						label: 'orgName',
						value: 'orgNo',
						children: 'child',
					}"
					v-model="organizationVal"
					:data="organizationOptions"
					placeholder="请选择预警机构"
					style="width: 240px"
				/>
			</div>
			<div class="f-item row items-center">
				<span>选择停车场：</span>
				<el-select
					:disabled="loading"
					v-model="parkingVal"
					filterable
					multiple
					collapse-tags
					collapse-tags-tooltip
					placeholder="请选择停车场"
					style="width: 240px"
					@change="parkingChange"
				>
					<el-option
						v-for="item in parkingOptions"
						:key="item.parkCode"
						:label="item.parkName"
						:value="item.parkCode"
					/>
				</el-select>
			</div>
			<div class="f-item row items-center">
				<span>是否开启车牌预警:</span>
				<el-switch
					v-model="isOpenWarning"
					class="ml-2"
					inline-prompt
					style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
					active-text="已开启"
					inactive-text="已关闭"
				/>
			</div>
		</div>
		<div class="content row justify-between">
			<div class="left">
				<div class="title">① 预警规则</div>
				<div class="tip">(开启车牌预警功能：从以下预警规则中至少配置一项)</div>
				<ProvinceItem
					:list="provinceList"
					@changeProvince="changeProvince"
					:isOpenWarning="isOpenWarning"
				/>
				<AllMatchItem
					:tagList="licenseList"
					@delLisence="delLisence"
					@addLicense="addLicense"
					:isOpenWarning="isOpenWarning"
				/>
				<PartMatchItem
					:tagList="codeList"
					@delLisence="delCode"
					@addCode="addCode"
					:isOpenWarning="isOpenWarning"
				/>
			</div>
			<div class="right">
				<div class="title">② 预警接收人</div>
				<div class="remind row">
					<span class="label row"
						><div>*</div>
						预警提醒：</span
					>
					<div class="r-item">
						<el-checkbox
							v-model="isOPenInWarning"
							label="开启入场提醒"
							size="large"
							:disabled="!isOpenWarning"
						/>
						<div class="tip">(预警车辆入场后发送入场短信)</div>
					</div>
					<div class="r-item">
						<el-checkbox
							:disabled="!isOpenWarning"
							v-model="isOPenOutWarning"
							label="开启出场提醒"
							size="large"
						/>
						<div class="tip">(预警车辆出场后发送入出场短信)</div>
					</div>
				</div>
				<TableItem
					ref="tableRef"
					:list="userList"
					:isOpenWarning="isOpenWarning"
					@delUser="delUser"
					@addUser="addUser"
				/>
			</div>
		</div>
		<div class="opr-panel row">
			<el-button @click="reset">取消</el-button>
			<el-button type="primary" @click="save">确定</el-button>
		</div>
	</div>
</template>

<script setup lang="ts">
import ProvinceItem from "./components/provinceItem.vue";
import AllMatchItem from "./components/allMatchItem.vue";
import PartMatchItem from "./components/partMatchItem.vue";
import TableItem from "./components/tableItem.vue";
import { setUserToken, getUserToken } from "@/utils/http/auth.ts";
import { ElMessage } from "element-plus";
import { ref, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import {
	getOrgNoList,
	getParkList,
	getRule,
	getUserList,
	addRule,
} from "@/api/plate.ts";
const loading = ref(false);
const isOpenWarning = ref(true);
const isOPenInWarning = ref(true);
const isOPenOutWarning = ref(true);

//机构筛选
const organizationVal = ref("");
const organizationOptions = ref([]);

//停车场筛选
watch(organizationVal, () => {
	parkingVal.value = [];
	getParkListFunc(organizationVal.value);
});
const parkingVal = ref([]);
const parkingOptions = ref([]);

//获取停车场列表
const getParkListFunc = async (id) => {
	loading.value = true;
	let list = await getParkList(id);
	parkingOptions.value = list;
	reset();
	loading.value = false;
};
const parkingChange = (arr) => {
	console.log("parkingChange", arr);
	let val = arr[0];
	if (!val) {
		reset();
		return;
	}
	getRules(val);
	getUserListFunc(val);
};

//获取规则
const rulesData = ref({});
const getRules = async (parkCode: string) => {
	console.log("parkCode", parkCode);
	const resRuleData = await getRule({ parkCode });
	console.log("resRuleData", resRuleData);
	if (!resRuleData) {
		rulesData.value = {};
		isOpenWarning.value = true;
		isOPenInWarning.value = true;
		isOPenOutWarning.value = true;
		provinceList.value = [];
		licenseList.value = [];
		codeList.value = [];
		return;
	}
	rulesData.value = resRuleData;

	if (rulesData?.value.reminderRange == 1) {
		isOPenInWarning.value = true;
		isOPenOutWarning.value = true;
	} else if (rulesData.value.reminderRange == 2) {
		isOPenInWarning.value = true;
		isOPenOutWarning.value = false;
	} else if (rulesData.value.reminderRange == 3) {
		isOPenInWarning.value = false;
		isOPenOutWarning.value = true;
	}
	const { provinceRule, carRule, fixedRule } = rulesData.value;
	isOpenWarning.value = rulesData.value.status == 2 ? false : true;
	provinceList.value = !provinceRule ? [] : provinceRule.split(",");
	licenseList.value = !carRule ? [] : carRule.split(",");
	codeList.value = !fixedRule ? [] : fixedRule.split(",");
};

//车牌首字
const provinceList = ref([]);
const changeProvince = (params: any) => {
	if (params.isChecked) {
		provinceList.value.push(params.province);
	} else {
		provinceList.value.splice(provinceList.value.indexOf(params.province), 1);
	}
	console.log("provinceList======", provinceList.value);
};

//匹配全车牌
const licenseList = ref([]);
//模糊匹配车牌
const codeList = ref([]);

const delLisence = (lisence: string) => {
	licenseList.value.splice(licenseList.value.indexOf(lisence), 1);
};

const addLicense = (lisence: string) => {
	if (licenseList.value.indexOf(lisence) > -1) {
		ElMessage({
			message: "已在列表中，请勿重复添加！",
			type: "error",
		});
	} else licenseList.value.push(lisence);
};

const addCode = (lisence: string) => {
	if (codeList.value.indexOf(lisence) > -1) {
		ElMessage({
			message: "已在列表中，请勿重复添加！",
			type: "error",
		});
	} else codeList.value.push(lisence);
};

const delCode = (lisence: string) => {
	codeList.value.splice(codeList.value.indexOf(lisence), 1);
};

// 预警接收人
const userList = ref([]);

const getUserListFunc = async (parkCode: string) => {
	let params = {
		pageNo: 1,
		pageSize: 100,
		param: {
			parkCode,
		},
	};
	const resData = await getUserList(params);
	console.log("resDataresData", resData);
	userList.value = resData?.list || [];
};
const delUser = (index: number) => {
	userList.value.splice(index, 1);
};

const addUser = () => {
	userList.value.push({
		userName: "",
		phone: "",
	});
	console.log("userList.value", userList.value);
};

const tableRef = ref(null);

// 保存数据
const save = () => {
	tableRef.value.checkForm((isPass) => {
		if (!isPass) return;
		let reminderRange = 1;
		if (isOPenInWarning.value && isOPenOutWarning.value) {
			reminderRange = 1;
		} else if (isOPenInWarning.value && !isOPenOutWarning.value) {
			reminderRange = 2;
		} else if (!isOPenInWarning.value && isOPenOutWarning.value) {
			reminderRange = 3;
		}

		let params = {
			parkCodeList: parkingVal.value ? parkingVal.value : ["0"],
			orgNo: organizationVal.value,
			provinceRule: provinceList.value?.join(",") || "",
			carRule: licenseList.value?.join(",") || "",
			fixedRule: codeList.value?.join(",") || "",
			reminderRange,
			status: isOpenWarning.value ? 1 : 2,
			userList: userList.value,
		};

		if (rulesData.value.id) {
			params.id = rulesData.value.id;
		}

		//请求接口
		console.log("paramsparams", params);

		addRule(params).then((res) => {
			// 预警规则新增成功
			ElMessage({
				message: "预警规则新增成功！",
				type: "success",
			});
			reset();
		});
	});
};

const reset = () => {
	parkingVal.value = [];
	isOpenWarning.value = true;
	isOPenInWarning.value = true;
	isOPenOutWarning.value = true;
	provinceList.value = [];
	licenseList.value = [];
	codeList.value = [];
	userList.value = [];
};

onMounted(async () => {
	const route = useRoute();
	const { token, orgNo } = route.query;
	if (token) {
		setUserToken(token);
	} else {
		setUserToken("");
	}

	if (orgNo) {
		organizationVal.value = orgNo;
	}

	let params = {
		orgNo: organizationVal.value, //所属组织/单位编号
		orgName: "", //组织机构名称（支持关键字）
	};
	loading.value = true;
	try {
		let orgNolist = await getOrgNoList(params);
		organizationOptions.value = orgNolist;
		getParkListFunc(organizationVal.value);
	} catch (error) {
		loading.value = false;
	}
});
</script>

<style scoped lang="scss">
.wrapper {
	padding: 60px 24px 24px;
	.filter {
		padding: 0 48px;
		.f-item {
			margin-right: 24px;
			span {
				margin-right: 8px;
			}
		}
	}
	.content {
		margin-top: 48px;
		.tip {
			color: rgb(217, 0, 27);
		}

		.left {
			margin-right: 16px;
			position: relative;
			border: 1px solid rgba($color: #000000, $alpha: 0.1);
			border-radius: 16px;
			padding: 24px 48px;
			box-sizing: border-box;
			.title {
				position: absolute;
				left: 24px;
				top: 0;
				transform: translateY(-50%);
				background-color: #fff;
				padding: 8px;
			}

			.province-panel {
				margin-top: 24px;
			}
		}
		.right {
			min-width: 560px;
			position: relative;
			border: 1px solid rgba($color: #000000, $alpha: 0.1);
			border-radius: 16px;
			padding: 24px;
			box-sizing: border-box;
			.title {
				position: absolute;
				left: 24px;
				top: 0;
				transform: translateY(-50%);
				background-color: #fff;
				padding: 8px;
			}
			.remind {
				.label {
					width: 80px;
					flex-shrink: 0;
					margin-top: 8px;
					div {
						color: rgb(217, 0, 27);
						font-size: 20px;
						margin-right: 2px;
					}
				}
				.r-item {
					margin-right: 24px;
				}
			}
		}
	}
	.opr-panel {
		margin-top: 24px;
		justify-content: flex-end;
	}
}
</style>
